let request=require('request');
let qs=require('querystring');

exports.Post=function Post(url,data){
    return new Promise((rev,reject)=>{
        let par=qs.stringify(data);
        let postData={
            method:'post',
            url,
            form:par,
            headers:{
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
            }
        };
        request(postData,(err,res,body)=>{
            if(err){
                return reject(err);
            }
            rev(res);
        });
    });
};

exports.Get=function Get(url){
    return new Promise((rev,reject)=>{
        request({
            url
        },(err,res,body)=>{
            if(err){
                return reject(err);
            }
            rev(res);
        });
    })
};

exports.Ajax=function Ajax(obj){
    return new Promise((rev,reject)=>{
        if(obj.form && typeof obj.form!=='string'){
            obj.form=qs.stringify(obj.form);
        }
        try{
            request(obj,(err,res,body)=>{
                if(err){
                    return reject(err);
                }
                rev(res);
            });
        }catch (e) {
            return reject(e);
        }
    })
};

exports.AjaxJson=function Ajax(obj){
    return new Promise((rev,reject)=>{
        if(obj.form && typeof obj.form!=='string'){
            obj.form=qs.stringify(obj.form);
        }
        request(obj,(err,res,body)=>{
            if(err){
                return reject(err);
            }
            try{
                res.body=JSON.parse(body);
            }catch (e) {
                return reject(e.message);
            }
            rev(res);
        });
    })

};

/**
 * unicode编码
 * @param str
 * @returns {string}
 */
exports.encodeUnicode=function(str) {
    var res = [];
    for ( var i=0; i<str.length; i++ ) {
        res[i] = ( "00" + str.charCodeAt(i).toString(16) ).slice(-4);
    }
    return "\\u" + res.join("\\u");
};
/**
 * unicode解码
 * @param str
 * @returns {string}
 */
exports.decodeUnicode=function(str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
};


